<?php

declare(strict_types=1);

namespace App\Controller\Backend;

use App\Constants\ErrorCode;
use App\Constants\SuccessCode;
use App\Controller\AbstractController;
use App\Exception\BusinessException;
use App\Model\Account;
use App\Model\AccountRecord;
use App\Model\OrderRecord;
use App\Model\Relation\UserRelationTeam;
use App\Model\User;
use App\Model\UserInvite;
use App\Request\Backend\User\UserBalanceEditRequest;
use App\Request\User\UserAccountEditRequest;
use App\Request\User\UserIdRequest;
use App\Request\User\UserPasswordEditRequest;
use App\Resource\Backend\UserResource;
use App\Resource\Backend\UserSearchResource;
use App\Resource\BaseCollection;
use App\Resource\BaseResource;
use App\Resource\OrderRecordsBackendResource;
use App\Resource\Team\UserRelationResource;
use App\Traits\PwdTool;
use Hyperf\Contract\SessionInterface;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;

class Users extends AbstractController
{
    use PwdTool;

    public function index(RequestInterface $request)
    {
        $where = [];
        if ($request->input('nick_name')) {
            $where[] = ['nick_name', 'like', '%' . $request->input('nick_name') . '%'];
        }

        if ($request->input('mobile')) {
            $where[] = ['mobile', '=', $request->input('mobile')];
        }

        if ($request->input('created_at')) {
            $dateTime = explode(',', $request->input('created_at'));
            $where[] = ['created_at', '>', $dateTime[0] . ' 00:00:01'];
            $where[] = ['created_at', '<', $dateTime[1] . ' 23:59:59'];
        }


        $list = User::where($where)->orderByDesc('id')->paginate();

        return UserResource::collection($list)->additional(['code' => 0, 'msg' => '成功']);
    }

    public function setUser(RequestInterface $request)
    {
        $user = User::find($request->input('id'));
        if ($request->input('nick_name')) {

            $user->nick_name = $request->input('nick_name');
        }
        if ($request->input('real_name')) {

            $user->real_name = $request->input('real_name');
        }
        if ($request->input('birthday')) {

            $user->birthday = $request->input('birthday');
        }
        if ($request->input('sex')) {

            $user->sex = $request->input('sex');
        }
        if ($request->input('address')) {

            $user->address = $request->input('address');
        }
        if ($request->input('password')) {

            $user->password_plaintext = $request->input('password');
            $user->password = $this->makePassword($request->input('password'));
        }

        $user->save();

        return new BaseResource();
    }


    public function searchList(RequestInterface $request)
    {
        $where = [];
        if ($request->input('nick_name')) {
            $where[] = ['nick_name', 'like', '%' . $request->input('nick_name') . '%'];
        }

        if ($request->input('mobile')) {
            $where[] = ['mobile', '=', $request->input('mobile')];
        }

        if ($request->input('created_at')) {
            $dateTime = explode(',', $request->input('created_at'));
            $where[] = ['created_at', '>', $dateTime[0] . ' 00:00:01'];
            $where[] = ['created_at', '<', $dateTime[1] . ' 23:59:59'];
        }


        $list = User::where($where)->orderByDesc('id')->paginate();

        return UserSearchResource::collection($list)->additional(['code' => 0, 'msg' => '成功']);
    }

    public function userBanYes(UserIdRequest $request)
    {
        $user = User::find($request->input('id'));
        $user->is_ban = 1;
        $user->save();

        return new BaseResource();
    }

    public function userBanNo(UserIdRequest $request)
    {
        $user = User::find($request->input('id'));
        $user->is_ban = 2;
        $user->save();

        return new BaseResource();
    }

    public function userCommissionYes(UserIdRequest $request)
    {
        $user = User::find($request->input('id'));
        $user->is_share_commission = 1;
        $user->save();

        return new BaseResource();
    }

    public function userCommissionNo(UserIdRequest $request)
    {
        $user = User::find($request->input('id'));
        $user->is_share_commission = 2;
        $user->save();

        return new BaseResource();
    }

    public function showPassword(UserIdRequest $request){

        $user = User::find($request->input('id'));

        return new BaseResource(SuccessCode::SUCCESS, ['password' => $user->password_plaintext]);
    }

    public function setPassword(UserPasswordEditRequest $request)
    {
        $user = User::find($request->input('id'));
        $user->password_plaintext = $request->input('password');
        $user->password = $this->makePassword($request->input('password'));
        $user->save();

        return new BaseResource();
    }

    public function editUserBalanceUsable(UserAccountEditRequest $request)
    {
        try {
            $amount = $request->input('amount');
            $uid = $request->input('uid');

            Db::transaction(function () use ($amount, $uid) {

                $account = Account::where('uid', $uid)->first();

                $before_amount = $account->balance_usable;
                $account->increment('balance_usable', $amount);
                $account->save();
                $after_amount = $account->balance_usable;

                $admin_user = ApplicationContext::getContainer()->get(SessionInterface::class)->get('admin_user');

                AccountRecord::create([
                    'user_id' => $uid,
                    'amount' => $amount,
                    'before_amount' => $before_amount,
                    'after_amount' => $after_amount,
                    'audit_user_id' => $admin_user->id,
                    'audit_user_name' => $admin_user->login_name,
                ]);
            });
            return new BaseResource();
        } catch (\Exception $e) {

            throw new BusinessException(ErrorCode::ACCOUNT_EDIT_ERROR);
        }
    }

    public function getUserBalanceRecord(RequestInterface $request)
    {
        $where = [];

        if ($request->input('id')) {

            $where[] = ['user_id', '=', $request->input('id')];
        }

        $list = AccountRecord::with('user')->where($where)->orderByDesc('id')->paginate();

        return new BaseCollection($list);
    }

    public function getChildren($uid)
    {
        $data = [];

        $level1 = UserInvite::where('uid', $uid)->first();

        if ($level1->left_uid) {

            $leftU = UserRelationTeam::find($level1->left_uid);
            $level2 = UserInvite::where('uid', $level1->left_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }
            $leftU->children = $this->getChildren($level1->left_uid);

            foreach ($leftU->children as $item ) {

                $item->children = $this->getChildren($item->id);
            }
            $data[] = $leftU;
        }
        if ($level1->center_uid) {

            $leftU = UserRelationTeam::find($level1->center_uid);
            $level2 = UserInvite::where('uid', $level1->center_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }
            $leftU->children = $this->getChildren($level1->center_uid);
            foreach ($leftU->children as $item ) {

                $item->children = $this->getChildren($item->id);
            }
            $data[] = $leftU;
        }
        if ($level1->right_uid) {

            $leftU = UserRelationTeam::find($level1->right_uid);
            $level2 = UserInvite::where('uid', $level1->right_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }
            $leftU->children = $this->getChildren($level1->right_uid);
            foreach ($leftU->children as $item ) {

                $item->children = $this->getChildren($item->id);
            }
            $data[] = $leftU;
        }

        return $data;
    }

    public function getUserRelationship(RequestInterface $request)
    {
        $data = \App\Model\Relation\UserInvite::with('children')->where('uid', $request->input('uid'))->select(['uid', 'invitation_uid'])->first();

        return new BaseResource(SuccessCode::SUCCESS, $data);


        // $level1 = UserInvite::where('uid', $request->input('uid'))->first();

        // $user = UserRelationTeam::find($request->input('uid'));

        // $user->children = UserRelationTeam::whereIn('id', $level1->child_nodes)->get();
        // return new BaseResource(SuccessCode::SUCCESS, $user);

        $children = [];

        $user->have_children = 0;

        if ($level1->left_uid || $level1->center_uid || $level1->right_uid ) {
            $user->have_children = 1;
        }

        if ($level1->left_uid) {

            $leftU = UserRelationTeam::find($level1->left_uid);
            $level2 = UserInvite::where('uid', $level1->left_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }

            $leftU->children = $this->getChildren($level1->left_uid);
            $children[] = $leftU;
        }
        if ($level1->center_uid) {

            $leftU = UserRelationTeam::find($level1->center_uid);

            $level2 = UserInvite::where('uid', $level1->center_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }

            $leftU->children = $this->getChildren($level1->center_uid);
            $children[] = $leftU;
        }
        if ($level1->right_uid) {

            $leftU = UserRelationTeam::find($level1->right_uid);
            $level2 = UserInvite::where('uid', $level1->right_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }
            $leftU->children = $this->getChildren($level1->right_uid);
            $children[] = $leftU;
        }
        $user->children = $children;

        return new BaseResource(SuccessCode::SUCCESS, $user);

        /*
        $level1 = UserInvite::with('user')
            ->with('leftUser')
            ->with('centUser')
            ->with('rightUser')
            ->whereIn('uid',
                UserInviteGrade::where('uid', $request->input('uid'))
                    ->where('grade', 1)
                    ->first()
                    ->child_nodes)->get(['uid', 'left_uid', 'center_uid', 'right_uid']);

        $level2 = UserInvite::with('user')
            ->with('leftUser')
            ->with('centUser')
            ->with('rightUser')
            ->whereIn('uid',
                UserInviteGrade::where('uid', $request->input('uid'))
                    ->where('grade', 2)
                    ->first()
                    ->child_nodes)->get(['uid', 'left_uid', 'center_uid', 'right_uid']);
        $level3 = UserInvite::with('user')
            ->with('leftUser')
            ->with('centUser')
            ->with('rightUser')
            ->whereIn('uid',
                UserInviteGrade::where('uid', $request->input('uid'))
                    ->where('grade', 3)
                    ->first()
                    ->child_nodes)->get(['uid', 'left_uid', 'center_uid', 'right_uid']);
        $level4 = UserInvite::with('user')
            ->with('leftUser')
            ->with('centUser')
            ->with('rightUser')
            ->whereIn('uid',
                UserInviteGrade::where('uid', $request->input('uid'))
                    ->where('grade', 4)
                    ->first()
                    ->child_nodes)->get(['uid', 'left_uid', 'center_uid', 'right_uid']);
        $level5 = UserInvite::with('user')
            ->with('leftUser')
            ->with('centUser')
            ->with('rightUser')
            ->whereIn('uid',
                UserInviteGrade::where('uid', $request->input('uid'))
                    ->where('grade', 5)
                    ->first()
                    ->child_nodes)->get(['uid', 'left_uid', 'center_uid', 'right_uid']);
        $level6 = UserInvite::with('user')
            ->with('leftUser')
            ->with('centUser')
            ->with('rightUser')
            ->whereIn('uid',
                UserInviteGrade::where('uid', $request->input('uid'))
                    ->where('grade', 6)
                    ->first()
                    ->child_nodes)->get(['uid', 'left_uid', 'center_uid', 'right_uid']);


        return new BaseResource(SuccessCode::SUCCESS, [
            $level1, $level2, $level3, $level4, $level5, $level6
        ]);
        */
    }

    public function getUserInvite(RequestInterface $request){

        $level1 = UserInvite::where('uid', $request->input('uid'))->first();

        $children = [];
        if ($level1->left_uid) {

            $leftU = UserRelationTeam::find($level1->left_uid);
            $level2 = UserInvite::where('uid', $level1->left_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }
            $leftU->children = $this->getChildren($level1->left_uid);
            $children[] = $leftU;
        }
        if ($level1->center_uid) {

            $leftU = UserRelationTeam::find($level1->center_uid);
            $level2 = UserInvite::where('uid', $level1->center_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }
            $leftU->children = $this->getChildren($level1->center_uid);
            $children[] = $leftU;
        }
        if ($level1->right_uid) {

            $leftU = UserRelationTeam::find($level1->right_uid);
            $level2 = UserInvite::where('uid', $level1->right_uid)->first();
            $leftU->have_children = 0;
            if ($level2->left_uid || $level2->center_uid || $level2->right_uid ) {
                $leftU->have_children = 1;
            }
            $leftU->children = $this->getChildren($level1->right_uid);
            $children[] = $leftU;
        }

        return new BaseResource(SuccessCode::SUCCESS, $children);
    }

    public function getUserOrderRecord(RequestInterface $request)
    {
        $where = [];
        if ($request->input('order_type')){

            $where[] = ['order_type', '=', $request->input('order_type')];
        }

        $where[] = ['uid', '=', $request->input('id')];
        $list = OrderRecord::where($where)->orderByDesc('updated_at')->paginate();

        return OrderRecordsBackendResource::collection($list)->additional([
            'code' => 0,
            'msg' => '成功',
        ]);
    }
}
